<template>
  <view class="order-container ">
    <view class="tab-box">
      <t-tabs lineHeight="4" justifyContent="space-between" :list="tabsList" :activeIndex="tabsIndex" @change="tabsChange"></t-tabs>
    </view>
    <view  class="order-content page_bg_FAFAFA padd30" >
     <scroll-view scroll-y="true" >
       <block v-for="(item, index) in filteredOrderList"
      				:key="item.orderId">
         <view class="goodsInfo">
          <com-goodsInfo   @viewDetail="viewOrderDetail"  @confirmReceipt="confirmOrderReceipt"  @deleteOrder="delOrder"    :goods-info="item" :totalAmount="item.totalAmount"    :showOrderStatus="true" :showBottomContent="true"></com-goodsInfo>
         
         </view>
       </block>
       <u-empty
              
           v-if="showEmpty"
                   mode="list"
           >
           </u-empty>
     </scroll-view>
     <u-loadmore marginTop="40" :status="status" line />
         

					</view>
				</block>
				<u-empty v-if="showEmpty" mode="list">
				</u-empty>
			</scroll-view>
			<u-loadmore marginTop="40" :status="status" line />
		</view>
	</view>
</template>

<script>
  export default {
    data() {
      return {
        showEmpty:false,
        tabsIndex: 0,
        tabsList: [{
          name: '全部',
        }, {
          name: '待发货',
        }, {
          name: '待确认'
        }, {
          name: '已完成'
        }],
        orderList: [],
        queryInfo: {
          limit: 6,
          page: 1
        },
        total: 0,
        orderId: '',
        status: '',
        isloading: false
      };
    },
    onLoad() {
      this.getOrderList(true)
    },
    computed: {
      filteredOrderList() {
        console.log('Current tabsIndex:', this.tabsIndex);
        switch(this.tabsIndex) {
              case 0:
                return this.orderList;
              case 1:
                return this.orderList.filter(item => item.status === 2);
              case 2:
                
                return this.orderList.filter(item => item.status === 3);
              case 3:
                console.log('过滤 已完成 订单');
                return this.orderList.filter(item => item.status === 5);
              default:
                console.warn('未知的 tabsIndex:', this.tabsIndex);
                return [];
            }
      }
    },
    
    methods: {
      async getOrderList(init,cb) {
        if(init||this.total> this.orderList.length){
          this.isloading = true;
            try {
              const { data } = await this.$http.get('/yaolexue-service-portal/order/pageMyOrder', this.queryInfo, { showLoading: true });
              this.orderList =init?data.items: [...this.orderList, ...data.items];
              this.total = data.total;
              
            } catch (error) {
              console.error('获取订单列表时发生错误:', error);
              uni.showToast({
                title: '获取订单列表失败',
                icon: 'none',
              });
            } finally {
              this.isloading = false;
              cb && cb();
            }
        }
       
        
      },
      onReachBottom() {
        if (this.isloading) return;
        if(this.queryInfo.page * this.queryInfo.limit >= this.total) return this.status = 'nomore'
       
        
      
        this.queryInfo.page += 1
        
        this.getOrderList()
      },
      tabsChange(index) {
        console.log(index);
        if (this.tabsIndex !== index || this.orderList.length === 0) {
              // 只有在选择的标签页发生变化或者orderList为空时才进行API调用
              this.tabsIndex = index;
              this.queryInfo.page = 1;
              this.orderList = [];
              this.getOrderList(true);
              this.showEmpty=false
            }
        
      },
      viewOrderDetail(goodsInfo) {
       
        uni.navigateTo({
          url: '/subPages/orderStatus/orderStatus?orderId=' + goodsInfo.orderId
        })
      },
     async confirmOrderReceipt(goodsInfo) {
        try {
            const res = await this.$http.post(`/yaolexue-service-portal/order/confirmReceipt/${goodsInfo.orderId}`);
            console.log('confirmOrderReceipt', res);
        
            uni.showToast({
              title: res.code === 200 ? res.data : '确认失败',
              icon: res.code === 200 ? 'success' : 'none',
            });
        
            await this.getOrderList(true);
          } catch (error) {
            console.error('确认收货时发生错误:', error);
            uni.showToast({
              title: '发生错误',
              icon: 'none',
            });
          }
      },
      async delOrder(goodsInfo) {
        console.log(goodsInfo);
        try {
            const res = await this.$http.delete(`/yaolexue-service-portal/order/delOrderById/${goodsInfo.orderId}`);
            console.log('delOrder', res);
        
            uni.showToast({
              title: res.code === 200 ? res.data : '删除失败',
              icon: res.code === 200 ? 'success' : 'none',
            });
             const index = this.orderList.findIndex(item => item.orderId === goodsInfo.orderId);
                
                if (index !== -1) {
                  // 如果找到了，就从orderList中删除这个订单
                  this.orderList.splice(index, 1);
                }
            await this.getOrderList(true);
          } catch (error) {
            console.error('确认收货时发生错误:', error);
            uni.showToast({
              title: '发生错误',
              icon: 'none',
            });
          }
      }
    }
  }
</script>

<style lang="scss" scoped>
	.order-container {

		.tab-box {
			position: sticky;
			top: 0;
			z-index: 999;

			::v-deep .tabs {
				// padding-left: 50rpx;
				// padding-right: 51rpx;
				z-index: 9999;
			}
		}

		.order-content {

			.goodsInfo {
				margin-top: 21rpx;
			}
		}

	}
</style>